package com.anteater.eattheant.view;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;

import com.anteater.eattheant.R;

public class Tunnel extends Group {

	public static float HEIGHT = 1.0f;
	public static float WIDTH = 1.0f;

	public static final short TOP = 1 << 0;
	public static final short BOTTOM = 1 << 1;
	public static final short LEFT = 1 << 2;
	public static final short RIGHT = 1 << 3;

	private final short i;
	private final short j;
	private final short orientation;

	private Context context;

	private static int texfiles[];

	public Tunnel(short i, short j, short orientation, GL10 gl, Context context) {
		super();

		this.i = i;
		this.j = j;
		this.orientation = orientation;
		this.context = context;

		bindFiles();

		if (orientation > 0) {
			Square square = new Square(1.0f);
			square.setTexture(new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
					1.0f, 1.0f }, loadTexture(gl));
			add(square);
		}
	}

	private static void bindFiles() {
		texfiles = new int[32];
		texfiles[TOP] = R.drawable.tunnel_t_64x64;
		texfiles[RIGHT] = R.drawable.tunnel_r_64x64;
		texfiles[BOTTOM] = R.drawable.tunnel_b_64x64;
		texfiles[LEFT] = R.drawable.tunnel_l_64x64;
		texfiles[TOP | RIGHT] = R.drawable.tunnel_tr_64x64;
		texfiles[TOP | BOTTOM] = R.drawable.tunnel_tb_64x64;
		texfiles[TOP | LEFT] = R.drawable.tunnel_tl_64x64;
		texfiles[RIGHT | BOTTOM] = R.drawable.tunnel_rb_64x64;
		texfiles[RIGHT | LEFT] = R.drawable.tunnel_rl_64x64;
		texfiles[BOTTOM | LEFT] = R.drawable.tunnel_bl_64x64;
		texfiles[TOP | RIGHT | BOTTOM] = R.drawable.tunnel_trb_64x64;
		texfiles[TOP | RIGHT | LEFT] = R.drawable.tunnel_trl_64x64;
		texfiles[TOP | BOTTOM | LEFT] = R.drawable.tunnel_tbl_64x64;
		texfiles[RIGHT | BOTTOM | LEFT] = R.drawable.tunnel_rbl_64x64;
		texfiles[TOP | RIGHT | BOTTOM | LEFT] = R.drawable.tunnel_trbl_64x64;
	}

	private int loadTexture(GL10 gl) {
		int texture[] = new int[1];

		gl.glGenTextures(1, texture, 0);

		Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),
				texfiles[orientation]);

		gl.glBindTexture(GL10.GL_TEXTURE_2D, texture[0]);

		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
				GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
				GL10.GL_NEAREST);

		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

		bitmap.recycle();

		return texture[0];
	}

	public short getI() {
		return i;
	}

	public short getJ() {
		return j;
	}

	public short getOrientation() {
		return orientation;
	}
}
